package com.example.mq.mqserver.datacenter.Impl;

import com.example.mq.mqserver.core.Binding;
import com.example.mq.mqserver.core.Exchange;
import com.example.mq.mqserver.core.MSGQueue;
import com.example.mq.mqserver.core.Message;
import com.example.mq.mqserver.datacenter.IDataBaseManager;
import com.example.mq.mqserver.datacenter.IDiskDataCenter;
import com.example.mq.mqserver.datacenter.IMessageFileManager;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class DiskDataCenterImpl implements IDiskDataCenter {
    private final IDataBaseManager dataBaseManager = new DataBaseManagerImpl();
    private final IMessageFileManager messageFileManager = new MessageFileManagerImpl();

    @Override
    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    @Override
    public void destroyDB() {
        dataBaseManager.destroyDB();
    }

    @Override
    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }
    @Override
    public void deleteExchange(Exchange exchange) {
        dataBaseManager.deleteExchange(exchange);
    }
    @Override
    public List<Exchange> selectAllExchange() {
        return dataBaseManager.selectAllExchange();
    }



    @Override
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        messageFileManager.createQueueFiles(queue.getName());
    }
    @Override
    public void deleteQueue(MSGQueue queue) throws IOException {
        dataBaseManager.deleteQueue(queue);
        messageFileManager.destroyFiles(queue.getName());
    }
    @Override
    public List<MSGQueue> selectAllQueue() {
        return dataBaseManager.selectAllQueue();
    }


    @Override
    public void insertBinding(Binding binding) {
        dataBaseManager.insertBind(binding);
    }
    @Override
    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }
    @Override
    public List<Binding> selectAllBinding() {
        return dataBaseManager.selectAllBinding();
    }


    @Override
    public void sendMessage(MSGQueue queue, Message message) throws IOException {
        messageFileManager.sendMessage(queue,message);
    }

    @Override
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue,message);
        //  删除消息后，判断是否GC
        if(messageFileManager.checkGC(queue.getName())) {
            messageFileManager.queueGC(queue);
        }
    }

    @Override
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
